import cmd
import os
import glob
import subprocess
import Pastor

class GencfaShell(cmd.Cmd):
    
    def __init__(self, pastor, spitter):
        self.pastor = pastor
        self.spitter = spitter
        self.gen_number = 0
        cmd.Cmd.__init__(self)
    
        
    def do_continue(self, arg):
        self.pastor.eval_pop()
        self.pastor.build_offspring()
        
        self.gen_number += 1
        ind_number = 0
        for individual in self.pastor.offspring:
            ind_number += 1
            name = "GEN" + str(self.gen_number) + "#" + str(ind_number)
            print("SPITTING INDIVIDUAL: " + str(individual.name()))
            self.spitter.spit_grammar(individual, name + ".cfdg")        
        self.pastor.next_gen()
    
    
    def help_continue(self):
        print "continue: proceeds to next generation of individuals"
    
    
    def do_score(self, arg):
        args = arg.split()
        self.pastor.add_eval((int(arg[0]), int(arg[2])))
    
    
    def help_score(self):
        print "score: receives score input for given individual. Usage: eval <individual> <score>"
    
    
    def do_evals(self, arg):
        print Pastor.print_tuple_list(self.pastor.evals)
    
    
    def help_evals(self):
        print "evals: displays current assigned scores for all individuals"
    
    
    def do_curpop(self, arg):
        print Pastor.print_pop_ext(self.pastor.current_pop)
        
        
    def help_curpop(self):
        print "curpop: prints current population"
    
    def do_imageall(self, arg):
        working_dir = self.spitter.path
        for file in glob.iglob(working_dir + "/output/*.*"):
            subprocess.call(["./cfdg", "-m 1000", file, file + ".png"])
        
    #shortcuts
    
    do_s = do_score
    do_go = do_continue
    do_ev = do_evals
    do_pop = do_curpop
